package com.efounder.pansoft.chat.emoji;

import android.content.Context;
import androidx.annotation.AttrRes;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.core.content.ContextCompat;
import androidx.viewpager.widget.ViewPager;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.ImageButton;
import android.widget.LinearLayout;

import com.efounder.chat.R;
import com.efounder.chat.adapter.ExpressionAdapter;
import com.efounder.chat.adapter.ExpressionPagerAdapter;
import com.efounder.chat.utils.SmileUtils;
import com.efounder.chat.widget.ExpandGridView;
import com.efounder.pansoft.chat.emoji.widget.AutoHeightLayout;
import com.efounder.recycleviewhelper.CommonAdapter;
import com.efounder.recycleviewhelper.base.ViewHolder;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;


public class EmojiView extends AutoHeightLayout {
    /**
     * 表情资源list
     **/
    private List<String> emoticonReslist;
    /**
     * 每页表情图标数量
     **/
    private final int expressionPagesize = 20;
    private int oldPosition = 0;// 记录上一次点的位置
    private int currentItem; // 当前页面
    private Context mContext;
    private LinearLayout emoticonContainer;
    private ViewPager expressionViewpager;
    private List<View> dots;
    //输入框
    private EditText editText;
    private RecyclerView recyclerView;
    private EmojiButtonAdater emojiButtonAdater;
    private List<EmojiButton> emojiButtonList;

    public EmojiView(Context context) {
        super(context, null);
        init(context, null);
    }

    public EmojiView(@NonNull Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
        init(context, attrs);
    }

    @Override
    public void onSoftKeyboardHeightChanged(int i) {
        Log.d("ddd", "onSoftKeyboardHeightChanged: " + i);
    }

    public EmojiView(@NonNull Context context, @Nullable AttributeSet attrs,
                     @AttrRes int defStyleAttr) {
        super(context, attrs);
        init(context, attrs);
    }

    private void init(Context context, AttributeSet attrs) {
        mContext = context;
        inflate(context, R.layout.layout_chatinput_emoji, this);

        emoticonContainer = findViewById(R.id.ll_face_container);
        expressionViewpager = (ViewPager) findViewById(com.efounder.chat.R.id.vPager);
        recyclerView = findViewById(R.id.recycleview);
        recyclerView.setLayoutManager(new LinearLayoutManager(mContext, LinearLayoutManager.HORIZONTAL, false));

        dots = new ArrayList<View>();
        dots.add(findViewById(com.efounder.chat.R.id.dot_1));
        dots.add(findViewById(com.efounder.chat.R.id.dot_2));
        dots.add(findViewById(com.efounder.chat.R.id.dot_3));
        dots.add(findViewById(com.efounder.chat.R.id.dot_4));
        dots.add(findViewById(com.efounder.chat.R.id.dot_5));


        for (View v : dots) {
            v.setVisibility(View.INVISIBLE);
        }

        initEmoji();
        initEmojiButton();
        initEmojiButtonData();

    }


    private void initEmoji() {
        emoticonReslist = getExpressionRes(89);
        // 初始化表情viewpager
        List<View> views = new ArrayList<View>();
//        View gv1 = getGridChildView(1);
//        View gv2 = getGridChildView(2);
//        View gv3 = getGridChildView(3);
//        View gv4 = getGridChildView(4);
//        View gv5 = getGridChildView(5);
//        views.add(gv1);
//        views.add(gv2);
//        views.add(gv3);
//        views.add(gv4);
//        views.add(gv5);
        View gv1 = getGridView();
        View gv2 = getGridView();
        views.add(gv1);
        views.add(gv2);
        expressionViewpager.setAdapter(new ExpressionPagerAdapter(views));

        expressionViewpager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }

            @Override
            public void onPageSelected(int position) {

                recyclerView.smoothScrollToPosition(position);
                emojiButtonAdater.setBgPosition(position);
                emojiButtonAdater.notifyDataSetChanged();
//
//                dots.get(oldPosition).setBackgroundResource(
//                        R.drawable.dot_normal);
//                dots.get(position)
//                        .setBackgroundResource(R.drawable.dot_focused);
//
//                oldPosition = position;
//                currentItem = position;

            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });
    }


    public void setEditext(EditText myEdit) {
        editText = myEdit;
    }

    /**
     * 获取表情资源
     *
     * @param getSum
     * @return
     */
    public List<String> getExpressionRes(int getSum) {
        List<String> emoticonReslist = new ArrayList<String>();
        for (int x = 1; x <= getSum; x++) {

            String filename = "ee_" + x;
            emoticonReslist.add(filename);
        }
        return emoticonReslist;
    }

    /**
     * 获取表情gridview
     *
     * @param i
     * @return
     */
    private View getGridChildView(int i) {
        View view = View.inflate(mContext, com.efounder.chat.R.layout.expression_gridview,
                null);
        ExpandGridView gv = (ExpandGridView) view.findViewById(com.efounder.chat.R.id.gridview);
        List<String> list = new ArrayList<String>();
        if (i == 1) {
            List<String> list1 = emoticonReslist.subList(0, expressionPagesize);
            list.addAll(list1);
        } else if (i == 2) {
            // list.addAll(emoticonReslist.subList(expressionPagesize,
            // emoticonReslist.size()));
            List<String> list2 = emoticonReslist
                    .subList(expressionPagesize, 40);
            list.addAll(list2);
        } else if (i == 3) {
            List<String> list3 = emoticonReslist.subList(40, 60);
            list.addAll(list3);

        } else if (i == 4) {
            List<String> list4 = emoticonReslist.subList(60, 80);
            list.addAll(list4);
        } else if (i == 5) {
            list.addAll(emoticonReslist.subList(80, emoticonReslist.size()));
        }
        list.add("delete_expression");
        final ExpressionAdapter expressionAdapter = new ExpressionAdapter(
                mContext, 1, list);
        gv.setAdapter(expressionAdapter);
        gv.setOnItemClickListener(new AdapterView.OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> parent, View view,
                                    int position, long id) {
                String filename = expressionAdapter.getItem(position);
                if (editText == null) {
                    return;
                }
                try {
                    // 文字输入框可见时，才可输入表情
                    // 按住说话可见，不让输入表情

                    if (filename != "delete_expression") { // 不是删除键，显示表情
                        // 这里用的反射，所以混淆的时候不要混淆SmileUtils这个类
                        @SuppressWarnings("rawtypes")
                        Class clz = Class.forName("com.efounder.chat.utils.SmileUtils");
                        Field field = clz.getField(filename);
                        editText.append(SmileUtils.getSmiledText(
                                mContext, (String) field.get(null)));
                    } else { // 删除文字或者表情
                        if (!TextUtils.isEmpty(editText.getText())) {
                            int selectionStart = editText
                                    .getSelectionStart();// 获取光标的位置
                            if (selectionStart > 0) {
                                String body = editText.getText()
                                        .toString();
                                String tempStr = body.substring(0,
                                        selectionStart);
                                int i = tempStr.lastIndexOf("[");// 获取最后一个表情的位置
                                if (i != -1) {
                                    CharSequence cs = tempStr.substring(i,
                                            selectionStart);
                                    if (SmileUtils.containsKey(cs
                                            .toString()))
                                        editText.getEditableText()
                                                .delete(i, selectionStart);
                                    else
                                        editText.getEditableText()
                                                .delete(selectionStart - 1,
                                                        selectionStart);
                                } else {
                                    editText.getEditableText()
                                            .delete(selectionStart - 1,
                                                    selectionStart);
                                }
                            }
                        }
                    }

                } catch (Exception e) {
                    e.printStackTrace();
                }

            }
        });
        return view;
    }

    private View getGridView() {
        View view = View.inflate(mContext, R.layout.qqstyle_layouy_emoji_gridview,
                null);
        GridView gv = (GridView) view.findViewById(R.id.gridview);
        List<String> list = new ArrayList<String>();
        list.addAll(emoticonReslist);
        list.add("delete_expression");
        final ExpressionAdapter expressionAdapter = new ExpressionAdapter(
                mContext, 1, list);
        gv.setAdapter(expressionAdapter);
        gv.setOnItemClickListener(new AdapterView.OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> parent, View view,
                                    int position, long id) {
                String filename = expressionAdapter.getItem(position);
                if (editText == null) {
                    return;
                }
                try {
                    // 文字输入框可见时，才可输入表情
                    // 按住说话可见，不让输入表情

                    if (filename != "delete_expression") { // 不是删除键，显示表情
                        // 这里用的反射，所以混淆的时候不要混淆SmileUtils这个类
                        @SuppressWarnings("rawtypes")
                        Class clz = Class.forName("com.efounder.chat.utils.SmileUtils");
                        Field field = clz.getField(filename);

                        int selectionStart = editText
                                .getSelectionStart();// 获取光标的位置
                        editText.getEditableText().insert(selectionStart,SmileUtils.getSmiledText(
                                mContext, (String) field.get(null)));
                    } else { // 删除文字或者表情
                        if (!TextUtils.isEmpty(editText.getText())) {
                            int selectionStart = editText
                                    .getSelectionStart();// 获取光标的位置
                            if (selectionStart > 0) {
                                String body = editText.getText()
                                        .toString();
                                String tempStr = body.substring(0,
                                        selectionStart);
                                int i = tempStr.lastIndexOf("[");// 获取最后一个表情的位置
                                if (i != -1) {
                                    CharSequence cs = tempStr.substring(i,
                                            selectionStart);
                                    if (SmileUtils.containsKey(cs
                                            .toString()))
                                        editText.getEditableText()
                                                .delete(i, selectionStart);
                                    else
                                        editText.getEditableText()
                                                .delete(selectionStart - 1,
                                                        selectionStart);
                                } else {
                                    editText.getEditableText()
                                            .delete(selectionStart - 1,
                                                    selectionStart);
                                }
                            }
                        }
                    }

                } catch (Exception e) {
                    e.printStackTrace();
                }

            }
        });
        return view;
    }

    //todo 针对下方recycleview的操作
    private void initEmojiButton() {

        emojiButtonList = new ArrayList<>();
        emojiButtonAdater = new EmojiButtonAdater(mContext, R.layout.layout_chatinput_emoji_button_item, emojiButtonList);
        recyclerView.setAdapter(emojiButtonAdater);
        emojiButtonAdater.setViewPager(expressionViewpager);

    }

    private void initEmojiButtonData() {
        emojiButtonList.clear();
        emojiButtonList.add(new EmojiButton("表情", R.drawable.qqstyle_icon_menu_emoji_focus, ""));
        emojiButtonList.add(new EmojiButton("收藏", R.drawable.qqstyle_icon_menu_heart, ""));
        emojiButtonAdater.notifyDataSetChanged();
    }

    private static class EmojiButton {
        public String name;
        public Object icon;
        public String type;

        public EmojiButton(String name, Object icon, String type) {
            this.name = name;
            this.icon = icon;
            this.type = type;
        }

    }

    private static class EmojiButtonAdater extends CommonAdapter<EmojiButton> {
        private int bgPosition = 0;
        private ViewPager viewPager;

        public void setBgPosition(int bg) {
            bgPosition = bg;
        }

        public void setViewPager(ViewPager viewPager) {
            this.viewPager = viewPager;
        }

        public EmojiButtonAdater(Context context, int layoutId, List<EmojiButton> datas) {
            super(context, layoutId, datas);
        }

        @Override
        protected void convert(ViewHolder holder, EmojiButton emojiButton, final int position) {
            ImageButton imageButton = holder.getView(R.id.imageButton);
            LinearLayout layout =  holder.getView(R.id.ll_button_layout);
            imageButton.setOnClickListener(new OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (viewPager != null)
                        viewPager.setCurrentItem(position);
                }
            });
            imageButton.setImageDrawable(ContextCompat.getDrawable(mContext, (Integer) emojiButton.icon));
            if (bgPosition == position) {
                layout.setBackgroundColor(ContextCompat.getColor(mContext, R.color.backColor));
            } else {
                layout.setBackgroundColor(ContextCompat.getColor(mContext, R.color.transparent));
            }
        }
    }
}
